<!--
 * @Author: your name
 * @Date: 2021-07-12 17:43:50
 * @LastEditTime: 2021-07-13 20:39:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \day1\vue_shop\src\components\power\Rights.vue
-->
<!--  -->
<template>
  <div>
      <daohang>
     <el-breadcrumb-item slot="guanli">角色管理</el-breadcrumb-item>
      <el-breadcrumb-item slot="liebiao">角色列表</el-breadcrumb-item>
    </daohang>
    <!-- 卡片视图区域 -->
      <el-card>
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="8">
          </el-col>
          <el-col :span="4">
            <el-button type="primary"
              >添加角色</el-button
            >
          </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <!-- border 边框stripe斑马线 -->
        <el-table :data="RolesList" style="width: 100%" border stripe>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 如果是第一行就加bdtop -->
              <el-row :class="['bdbottom', i1=== 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                   <el-tag>{{item1.authName}}</el-tag>
                   <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二和三级权限 -->
                <el-col :span="19">
                  <el-row :class="['bdbottom', i2=== 0 ? 'bdtop' : '', 'vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                    <el-col>
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                    <el-tag type="warning" :class="['bdbottom', i3=== 0 ? 'bdtop' : '', 'vcenter']" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="remove(scope.row,item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
         <!-- //索引列 -->
         <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
              >编辑</el-button>
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
              >删除</el-button>
              <!-- 分配角色按钮   鼠标是否可进入到 tooltip 中:enterable="false" -->
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="showSetRightDialog(scope.row)"
                >分配权限</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 分配权限对话框 -->
      <el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="30%"
  @close="setRightDialogClosed"
 >
  <el-tree
  :data="rightList"
  :props="treeProps"
  show-checkbox node-key="id" default-expand-all 
  :default-checked-keys="defkeys" ref="treeRef">
</el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
    </div>
  </div>
</template>

<script>
import Daohang from 'components/common/Daohang.vue'
export default {
  components: {
    Daohang
  },
  data() {
    //获取用户列表的参数对象
    return { 
      RolesList: [],
       // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible:false,
      rightList:[],
       // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认勾选的节点的 key 的数组
      defkeys:[116],
      //当前即将分配权限的角色id
      roleId:''

    }
  },
  mounted() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.RolesList = res.data
     // console.log(this.RolesList)
      //console.log(res)
    },
    //删除用户
    // 根据Id删除对应的用户信息
    async remove(role,rightId) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      //this.getData()
      role.children = res.data
    },
   async showSetRightDialog(role){
      this.roleId = role.id
      //获取所有权限的数据
      const {data:res}=await this.$http.get('rights/tree')
      if(res.meta.status!==200) return this.$message.error("获取失败")
      //把获取到的权限数据保存到data中
      this.rightList=res.data
      //console.log(this.rightList)
      //展示分配权限对话框
      //递归获取三级节点id
      this.getDefkeys(role,this.defkeys)
      this.setRightDialogVisible=true
    },
    //通过递归的形式获取三级权限下所有id,并保存到defkeys数组中
    getDefkeys(node,arr){
      if(!node.children) return arr.push(node.id)
      //console.log(arr)
      node.children.forEach(item=>this.getDefkeys(item,arr))
    },
    //监听分配权限的对话框
    setRightDialogClosed(){
      this.defkeys=[]
    },
    //点击为角色分配权限
   async allotRights(){
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //转换成字符串
      const idStr = keys.join(',')
      //console.log(idStr)
     const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        //请求参数：通过 `请求体` 发送给后端,角色id
        {rids:idStr}
      )
      console.log(res)
        if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }

      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
      
    }
    
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom{
  border-bottom:1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>

